/**
 * Project 67th
 */


#ifndef _TCPCONNECTION_H
#define _TCPCONNECTION_H

#include "SocketIO.h"
#include "Socket.h"
#include "InetAddress.h"
#include <memory>
#include <functional>
using std::shared_ptr;
using std::function;
using std::bind;

//前向声明
class TcpConnection;

using TcpConnectionPtr = shared_ptr<TcpConnection>;

using TcpConnectionCallback = 
function<void(const TcpConnectionPtr &)>;

class TcpConnection 
: public std::enable_shared_from_this<TcpConnection>
{
public: 
    /**
     * @param fd
     */
    explicit TcpConnection(int fd);

    ~TcpConnection();

    string receive();

    /**
     * @param msg
     */
    void send(const string & msg);

    string toString();

    bool isClosed();


    //规范：如果函数中会利用传参进行移动语义的使用
    //那么参数形式往往写成右值引用
    //否则就写成const左值引用
    void setNewConnectionCallback(const TcpConnectionCallback & cb);
    void setMessageCallback(const TcpConnectionCallback & cb);
    void setCloseCallback(const TcpConnectionCallback & cb);

    void handleNewConnectionCallback();
    void handleMessageCallback();
    void handleCloseCallback();

private:
    InetAddress getLocalAddr();
    InetAddress getPeerAddr();

private: 
    SocketIO _sockIO;

    //对于TcpConnection对象
    //每一个对象代表一条连接
    //用以下的三个数据成员分别存储
    //这条连接对应的文件描述符，以及双端的地址信息
    Socket _sock;
    InetAddress _localAddr;
    InetAddress _peerAddr;

    TcpConnectionCallback _onNewConnection;
    TcpConnectionCallback _onMessage;
    TcpConnectionCallback _onClose;
};

#endif //_TCPCONNECTION_H
